<script lang="ts" setup>
import {
  getListByConditions,
  getOneByCondition,
  insertOne,
  logicalDeleteById,
  physicalDeleteById,
  updateOne,
  urls
} from '@/index';
import type { DrawerModel, ProjectProduction, ProjectProject } from '@/index.d';
import type { FormInstance, FormRules } from 'element-plus';
import { useRequest } from 'vue-request';

const drawerModel = defineModel<DrawerModel<ProjectProject>>('drawerModel', {
  required: true
});

const title = computed(() => {
  const data = drawerModel.value.data;
  if (data) {
    return (data.longProjectName as string) + '产品清单';
  } else {
    return '获取数据错误';
  }
});

const {
  data: getRecordListData,
  run: getRecordListRun,
  loading: getRecordListLoading
} = useRequest(() =>
  getListByConditions<ProjectProduction>(urls.projectProduction, {
    projectId: drawerModel.value.data?.id
  })
);

watch(
  () => drawerModel.value.visible,
  (value: boolean) => {
    value && getRecordListRun();
  }
);
const operateType = ref<'insert' | 'update'>('insert');
const formData = reactive<ProjectProduction>({
  projectId: drawerModel.value.data?.id
});
const formDataRef = ref<FormInstance>();
interface FormDataRules {
  productionReference: string;
}

const formDataRules = computed(() => {
  switch (operateType.value) {
    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }]
      });

    case 'update':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }]
      });
  }
});

const dataOperate = async (type: 'logicalDelete' | 'physicalDelete' | 'update', id: number) => {
  if (type === 'physicalDelete') {
    const res = await physicalDeleteById(urls.projectProduction, id);
    if (res) {
      getRecordListRun();
    }
  } else if (type === 'logicalDelete') {
    const res = await logicalDeleteById(urls.projectProduction, id);
    if (res) {
      getRecordListRun();
    }
  } else if (type === 'update') {
    const res = await getOneByCondition(urls.projectProduction, 'id', id);
    setFormData(res as ProjectProduction);
    operateType.value = 'update';
    inputCardVisble.value = true;
  }
};
const saveProduct = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate().then(async valid => {
    if (valid) {
      if (!formData.id) {
        const res = (await insertOne<ProjectProduction>(
          urls.projectProduction,
          formData
        )) as ProjectProduction;
        if (res) {
          setFormData(res);
          operateType.value = 'update';
          setFormData(res);
          getRecordListRun();
        }
      } else {
        const tempFormData: ProjectProduction = {
          id: formData.id,
          productionReference: formData.productionReference
        };

        const res = (await updateOne<ProjectProduction>(
          urls.projectProduction,
          tempFormData
        )) as ProjectProject;
        if (res) {
          getRecordListRun();
        }
      }
    }
  });
};
const setFormData = (data: ProjectProduction) => {
  formData.id = data.id;
  formData.projectId = data.projectId;
  formData.productionReference = data.productionReference;
};

const inputCardVisble = ref<boolean>(false);

const showInputCard = () => {
  inputCardVisble.value = true;
};

const closeInputCard = () => {
  inputCardVisble.value = false;
  delete formData.id;
  delete formData.productionReference;
};
const showLogicalDeleted = ref<boolean>(false);
</script>
<template>
  <el-drawer v-model="drawerModel.visible" :title destroy-on-close size="40%">
    <template #default>
      <el-card>
        <template #header>
          <el-button type="success" @click="showInputCard">新增产品</el-button>
          &nbsp;&nbsp;&nbsp;&nbsp; 展示逻辑删除数据：<el-switch v-model="showLogicalDeleted" />
        </template>
        <template #default>
          <HqTable
            :base-url="urls.projectProduction"
            title="无损操作记录"
            :table-data="getRecordListData"
            :loading="getRecordListLoading"
            :on-handle-reload="getRecordListRun"
          >
            <template #columns>
              <HqTableColumn label="生产令号" prop="productionReference" />
              <HqTableColumn label="操作" v-if="!inputCardVisble">
                <template #default="{ row }">
                  <el-button type="primary" link @click="dataOperate('update', row.id)">
                    修改
                  </el-button>
                  <el-popconfirm
                    title="确认逻辑删除吗？"
                    @confirm="dataOperate('logicalDelete', row.id)"
                  >
                    <template #reference>
                      <el-button type="warning" link> 逻辑删除 </el-button>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm
                    title="确认物理删除吗？"
                    @confirm="dataOperate('physicalDelete', row.id)"
                  >
                    <template #reference>
                      <el-button type="danger" link> 物理删除 </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </HqTableColumn>
            </template>
          </HqTable>
        </template>
      </el-card>
      <br />
      <el-card v-if="inputCardVisble">
        <template #header> {{ operateType === 'insert' ? '新增' : '修改' }}产品 </template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row>
              <el-col v-show="true">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </el-col>
              <el-col v-show="true">
                <el-form-item label="项目id" prop="projectId">
                  <el-input v-model="formData.projectId" readonly />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="生产令号" prop="productionReference">
                  <el-input v-model="formData.productionReference" />
                </el-form-item>
              </el-col>
            </el-row>
          </hq-form>
        </template>
        <template #footer>
          <el-button
            type="success"
            @click="saveProduct(formDataRef)"
            :disabled="!formData.productionReference"
          >
            保存产品
          </el-button>
          <el-button type="danger" @click="closeInputCard">关闭输入</el-button>
        </template>
      </el-card>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.el-row {
  margin-bottom: 10px;
}
</style>
